import React, { PropTypes } from 'react';
import { connect } from 'dva';
import { Table, Pagination, Dropdown, Button, Menu, Icon, Modal, message } from 'antd';
import filterItemCreate from './FilterItem'
import dataEditCreate from '../addons/DataEdit'
import * as datetime from '../../utils/datetime'
import numeral from 'numeral';

const renderDIVI = (num) => {
    if (num) {
        num = num * 100
        return numeral(num).format('0.00') + '%'
    }
    return "";
};

const acblColumns = [
    { title: '日期', dataIndex: 'dtid', width: 100 },
    { title: '余额折人民币', width: 100, dataIndex: 'acbl' },
]

const inrtColumns = [
    { title: '日期', dataIndex: 'dtid', width: 100 },
    { title: '利率', width: 100, dataIndex: 'inrt' }
]
const diviColumns = [
    { title: '员工号', width: 80, dataIndex: 'emno' },
    { title: '员工名称', width: 100, dataIndex: 'emnm' },
    { title: '所属部门', width: 120, dataIndex: 'dpnm' },
    { title: '类别', width: 80, dataIndex: 'dsty' },
    { title: '开始日期', width: 100, render: data => datetime.format(data.dsdt, "yyyy-MM-dd") },
    { title: '截至日期', width: 100, render: data => datetime.format(data.wodt, "yyyy-MM-dd") },
    { title: '认定值', width: 100, render: data => renderDIVI(data.dsvl) }
]

class ListReportTable extends React.Component {
    constructor(props) {
        super(props);
    }
    componentDidMount() {
        const count = this.props.columns.length
        if (count === 0) {
            this.getRepInfo()
        }
    }
    componentWillReceiveProps(nextProps) {
        const count1 = nextProps.columns.length
        const count2 = this.props.columns.length
        if (count1 > 0 && count2 === 0) {
            this.query({ record: nextProps.record })
        }
    }
    rowClickHandler(d, i, e) {
        if (e.target.tagName === "TD") {
            const list = this.props.dataSource
            const key = this.props.keyColumn
            let selectedRowKeys = [list[i][key]]
            const reportName = this.props.reportName
            const model = "ListReport_" + reportName
            this.props.dispatch({
                type: `${model}/setSelectedRowKeys`,
                payload: { selectedRowKeys, currRowIndex: i }
            });
        }
    }
    rowClassName(record, index) {
        const rowKeys = this.props.selectedRowKeys
        if (rowKeys.length > 0) {
            const key = this.props.keyColumn
            const list = this.props.dataSource
            let rowKey = list[index][key]
            if (rowKey === rowKeys[0]) {
                return "selected-row"
            }
        }
    }
    pageChangeHandler(page) {
        const { pageSize, sorter, filters } = this.props;
        this.query({ page, pageSize, sorter, filters })
    }
    pageSizeChangeHandler(e) {
        const pageSize = parseInt(e.key)
        const { sorter, filters } = this.props;
        this.query({ page: 1, pageSize, sorter, filters })
    }
    getRepInfo() {
        const { reportName, permID } = this.props
        const model = "ListReport_" + reportName
        this.props.dispatch({
            type: `${model}/fetchRepInfo`,
            payload: { reportName, permID }
        });
    }
    reload() {
        const { currentPage, pageSize, sorter, filters } = this.props;
        this.query({ page: currentPage, pageSize, sorter, filters })
    }
    handleTableChange(_, filters2, sorter) {
        const { currentPage, pageSize, filters } = this.props;
        this.query({ page: currentPage, pageSize, sorter, filters })
    }
    query({ record, page, pageSize, sorter, filters }) {
        const { reportName, permID } = this.props
        const model = "ListReport_" + this.props.reportName
        if (!record) {
            record = this.props.record
        }
        if (!page) {
            page = this.props.currentPage
        }
        if (!pageSize) {
            pageSize = this.props.pageSize
        }
        if (!sorter) {
            sorter = this.props.sorter
        }
        if (!filters) {
            filters = this.props.filters
        }
        this.props.dispatch({
            type: `${model}/fetchData`,
            payload: { reportName, record, page, pageSize, sorter, filters, permID }
        });
    }
    handleFilterVisibleChange(name, visible) {
        if (!visible) {
            return
        }
        const model = "ListReport_" + this.props.reportName
        let filterName = null
        if (visible) {
            filterName = name
        }
        this.props.dispatch({
            type: `${model}/setVisibleFilterName`,
            payload: { visibleFilterName: filterName }
        });
    }
    handleFilterOk(colName, filter) {
        let filters = this.props.filters
        if (colName !== undefined && filter !== undefined) {
            const filterVal = { [colName]: filter }
            let newFilters = { ...filters, ...filterVal }
            if (filter === null) {
                delete newFilters[colName]
            }
            filters = newFilters
        }
        this.query({ filters })
    }
    getFilterDropdown(col) {
        const model = "ListReport_" + this.props.reportName
        let type = 'text'
        let dataType = 'string'
        let data = null
        if (col.dataType === "number" || col.dataType === "int" || col.dataType === "float") {
            type = "number"
            dataType = "number"
        } else if (col.dataType === "date") {
            type = "date"
            dataType = "date"
        } else if (col.dataType === "bool") {
            type = "radio-group"
            dataType = "bool"
            data = [{ value: '1', label: '是' }, { value: '0', label: '否' }]
        }
        let cont = {
            label: col.title,
            name: col.name,
            type,
            dataType,
            data
        }
        const FilterItem = filterItemCreate(model, col.name)
        return <FilterItem daoName={model} control={cont} canSelectOR={true} onOk={this.handleFilterOk.bind(this)} />
    }
    createHandler() {
        const {  permID, odsDate, cmDate, menus, FTPDate } = this.props
        let sjy = ""
        menus.map((c, i) => {
            if (permID === c.ID) {
                sjy = c.SJY
            }
        })
        const form = this.refs.paramForm.getForm()
        form.validateFields((err, values) => {
            if (!err) {
                const controls = this.props.controls
                controls.map((c, i) => {
                    if (c.dataType === "date" || c.dataType === "datetime") {
                        values[c.name] = !values[c.name] ? "" : datetime.format(values[c.name], "yyyy-MM-dd")
                    } else {
                        values[c.name] = values[c.name] === undefined ? "" : values[c.name]
                    }
                    if (c.multiple || c.type === 'checkbox-group') {
                        values[c.name] = values[c.name].join(',');
                    }
                })
                let date = "";
                if (values.date != undefined) {
                    date = datetime.format(new Date(values.date), "yyyyMMdd")
                }
                if (sjy === "EDW") {
                    let scd = datetime.format(cmDate, "yyyyMMdd")
                    if (date > scd) {
                        message.error('超出系统数据日期，数仓数据日期为【' + datetime.format(cmDate, "yyyy-MM-dd") + '】');
                        return;
                    }
                } else if (sjy === "ODS") {
                    let odsd = datetime.format(odsDate, "yyyyMMdd")
                    if (date > odsd) {
                        message.error('超出系统数据日期，ODS数据日期为【' + datetime.format(odsDate, "yyyy-MM-dd") + '】');
                        return;
                    }
                } else {
                    let ftpd = datetime.format(FTPDate, "yyyyMMdd")
                    if (date > ftpd) {
                        message.error('超出系统数据日期，FTP数据日期为【' + datetime.format(FTPDate, "yyyy-MM-dd") + '】');
                        return;
                    }
                }
                this.query({ record: values })
            }
        });
    }
    hideHandler() {
        const reportName = this.props.reportName
        const model = "ListReport_" + reportName
        this.props.dispatch({
            type: `${model}/hiddenAcblDivi`,
            payload: {}
        });
    }
    acbl1Handler() {
        const { record, acbl } = this.props
        let { sdate, edate } = acbl
        if (!sdate) {
            sdate = record.date.substring(0, 7) + "-01"
        }
        if (!edate) {
            edate = record.date
        }
        this.queryACBL({ sdate, edate })
    }
    acbl2Handler() {
        const form = this.refs.acblForm.getForm()
        form.validateFields((err, values) => {
            if (!err) {
                const sdate = datetime.format(values["sdate"], "yyyy-MM-dd")
                const edate = datetime.format(values["edate"], "yyyy-MM-dd")
                this.queryACBL({ sdate, edate })
            }
        });
    }
    inrt1Handler() {
        const { record, inrt } = this.props
        let { sdate, edate } = inrt
        if (!sdate) {
            sdate = record.sdate
        }
        if (!edate) {
            edate = record.edate
        }
        this.queryINRT({ sdate, edate })
    }
    inrt2Handler() {
        const form = this.refs.acblForm.getForm()
        form.validateFields((err, values) => {
            if (!err) {
                const sdate = datetime.format(values["sdate"], "yyyy-MM-dd")
                const edate = datetime.format(values["edate"], "yyyy-MM-dd")
                this.queryINRT({ sdate, edate })
            }
        });
    }
    queryACBL({ sdate, edate }) {
        const { reportName, selectedRowKeys } = this.props
        if (selectedRowKeys.length === 0) {
            message.info("请先点击选择一行数据！", 2);
            return
        }
        const acid = selectedRowKeys[0]
        const model = "ListReport_" + reportName
        this.props.dispatch({
            type: `${model}/fetchACBL`,
            payload: { reportName, sdate, edate, acid }
        });
    }
    queryINRT({ sdate, edate }) {
        const { reportName, selectedRowKeys } = this.props
        if (selectedRowKeys.length === 0) {
            message.info("请先点击选择一行数据！", 2);
            return
        }
        const acid = selectedRowKeys[0]
        const model = "ListReport_" + reportName
        this.props.dispatch({
            type: `${model}/fetchINRT`,
            payload: { reportName, sdate, edate, acid }
        });
    }
    diviHandler() {
        const { reportName, selectedRowKeys } = this.props
        if (selectedRowKeys.length === 0) {
            message.info("请先点击选择一行数据！", 2);
            return
        }
        const model = "ListReport_" + reportName
        this.props.dispatch({
            type: `${model}/fetchDIVI`,
            payload: { reportName }
        });
    }
    exportData() {
        const { reportName, permID } = this.props
        const model = "ListReport_" + reportName
        this.props.dispatch({
            type: `${model}/exportData`,
            payload: { reportName, permID }
        });
    }
    attachColumns(columns) {
        const { visibleFilterName, filters } = this.props
        const leafNode = col => {
            if (!col.children || col.children.lenght === 0) {
                col.filterDropdown = this.getFilterDropdown(col)
                let visible = false;
                if (col.name === visibleFilterName) {
                    visible = true;
                }
                col.filterDropdownVisible = visible;
                col.filteredValue = filters[col.name] ? [1] : [];
                col.onFilterDropdownVisibleChange = this.handleFilterVisibleChange.bind(this, col.name)
                if (col.dataType === "number" || col.dataType === "float") {
                    col.className = "column-money"
                }
            } else {
                col.children.map(ccol => {
                    leafNode(ccol)
                })
            }
        }
        columns.map(col => {
            leafNode(col)
        })
    }
    getColumnsWidth(columns) {
        const getWidth = col => {
            if (!col.children || col.children.lenght === 0) {
                return col.width ? col.width : 90
            } else {
                let width = 0
                col.children.map(ccol => {
                    width = width + getWidth(ccol)
                })
                return width
            }
        }
        let width = 0
        columns.map(col => {
            width = width + getWidth(col)
        })
        return width
    }
    clearFilter() {
        const { reportName, permID } = this.props
        const daoName = "ListReport_" + reportName
        this.props.dispatch({
            type: `${daoName}/clearFilter`,
            payload: { reportName, permID }
        });
    }
    render() {
        const { controls, columns, width, height, bordered, dataSource, loading, size, currentPage, pageSize, total, offsetHeight, offsetWidth, keyColumn, userIDColumn, record, reportName } = this.props;
        if (!columns || columns.lenght === 0) {
            return (<div></div>)
        }
        this.attachColumns(columns)
        let x = width, y = height
        if (width === 0) {
            x = this.getColumnsWidth(columns)
        }
        if (height === 0) {
            y = offsetHeight - 175 - 42
            if (x > offsetWidth) {
                y = y - 20
            }
        }
        const menu2 = (<Menu onClick={this.pageSizeChangeHandler.bind(this)}>
            <Menu.Item key="10">每页显示10行</Menu.Item>
            <Menu.Item key="20">每页显示20行</Menu.Item>
            <Menu.Item key="30">每页显示30行</Menu.Item>
            <Menu.Item key="40">每页显示40行</Menu.Item>
            <Menu.Item key="50">每页显示50行</Menu.Item>
        </Menu>);
        let exportButton = ""
        if (this.props.canExport) {
            exportButton = <Button style={{ margin: 5 }} key="b_exportData" onClick={this.exportData.bind(this)}>导出excel</Button>
        }
        const getRowKey = (record) => {
            return "" + record[keyColumn] + "_" + record[userIDColumn]
        }
        const { canACBL, canINRT, canDIVI, acbl, divi, inrt, currRowIndex, titleColNames } = this.props
        let bDatas = []
        if (canACBL) {
            bDatas.push({ value: '2', label: '查看余额变动', onClick: this.acbl1Handler.bind(this) })
        }
        if (canINRT) {
            bDatas.push({ value: '3', label: '查看利率变动', onClick: this.inrt1Handler.bind(this) })
        }
        if (canDIVI) {
            bDatas.push({ value: '4', label: '查看账户关系', onClick: this.diviHandler.bind(this) })
        }
        bDatas.push({ value: '1', label: '生成报表', onClick: this.createHandler.bind(this) })
        let len = controls.length <= 1 ? controls.length + 1 : controls.length
        const button = { name: 'createButton', type: 'button-group', data: bDatas, grid: parseFloat(1) / (len) }
        let controls2 = [...controls, button]
        const daoName = "ListReport_" + reportName;
        const EditFrom = dataEditCreate(daoName);
        let window = null
        if (currRowIndex >= 0 && (canACBL || canDIVI)) {
            let titleColIDs = []
            titleColNames.map(
                colName => {
                    for (let i in columns) {
                        if (columns[i].name === colName) {
                            titleColIDs.push(columns[i].dataIndex)
                            break
                        }
                    }
                }
            )
            const getTitles = () => { const names = titleColIDs.map(colID => dataSource[currRowIndex][colID]); return names.join("-") }
            if (canACBL && acbl.visible) {
                const EditACBLFrom = dataEditCreate(daoName);
                const acblControls = [
                    { name: "sdate", label: "开始日期", type: "date", grid: 10, dataType: "date" },
                    { name: "edate", label: "截至日期", type: "date", grid: 10, dataType: "date" },
                    { name: 'lookButton', type: 'button-group', data: [{ value: '1', label: '查看', onClick: this.acbl2Handler.bind(this) }], grid: 4 }
                ]
                const acblRecord = {
                    sdate: acbl.sdate,
                    edate: acbl.edate,
                }
                window = <Modal title={"余额变动  " + getTitles()} width={800} visible={true} onCancel={this.hideHandler.bind(this)}>
                    <div style={{ marginBottom: 5 }}>
                        <EditACBLFrom ref="acblForm" daoName={daoName} controls={acblControls} record={acblRecord} selectFirst={false} clearItemMargin={true} />
                    </div>
                    <Table
                        columns={acblColumns}
                        dataSource={acbl.list}
                        loading={loading}
                        rowKey={record => record.dtid}
                        scroll={{ x: 300, y: 500 }}
                        bordered={true}
                        pagination={false}
                    />
                </Modal>
            }
            if (canINRT && inrt.visible) {
                const EditACBLFrom = dataEditCreate(daoName);
                const inrtControls = [
                    { name: "sdate", label: "开始日期", type: "date", grid: 10, dataType: "date" },
                    { name: "edate", label: "截至日期", type: "date", grid: 10, dataType: "date" },
                    { name: 'lookButton', type: 'button-group', data: [{ value: '1', label: '查看', onClick: this.acbl2Handler.bind(this) }], grid: 4 }
                ]
                const inrtRecord = {
                    sdate: inrt.sdate,
                    edate: inrt.edate,
                }
                window = <Modal title={"利率变动  " + getTitles()} width={800} visible={true} onCancel={this.hideHandler.bind(this)}>
                    <div style={{ marginBottom: 5 }}>
                        <EditACBLFrom ref="acblForm" daoName={daoName} controls={inrtControls} record={inrtRecord} selectFirst={false} clearItemMargin={true} />
                    </div>
                    <Table
                        columns={inrtColumns}
                        dataSource={inrt.list}
                        loading={loading}
                        rowKey={record => record.dtid}
                        scroll={{ x: 300, y: 500 }}
                        bordered={true}
                        pagination={false}
                    />
                </Modal>
            }
            if (canDIVI && divi.visible) {
                window = <Modal title={"账户认定关系  " + getTitles()} width={800} visible={true} onCancel={this.hideHandler.bind(this)}>
                    <Table
                        columns={diviColumns}
                        dataSource={divi.list}
                        loading={loading}
                        rowKey={record => record.id}
                        scroll={{ x: 680, y: 500 }}
                        bordered={true}
                        pagination={false}
                    />
                </Modal>
            }
        }
        return (
            <div>
                <div style={{ marginBottom: 5 }}>
                    <EditFrom ref="paramForm" daoName={daoName} controls={controls2} record={record} selectFirst={false} clearItemMargin={true} />
                </div>
                <Table
                    columns={columns}
                    dataSource={dataSource}
                    loading={loading}
                    onRowClick={this.rowClickHandler.bind(this)}
                    rowKey={record => getRowKey(record)}
                    scroll={{ x, y }}
                    bordered={bordered}
                    pagination={false}
                    size={size}
                    onChange={this.handleTableChange.bind(this)}
                    rowClassName={this.rowClassName.bind(this)}
                />
                <div>
                    <Dropdown overlay={menu2} trigger={['click']} >
                        <Button type="ghost" style={{ margin: 5 }}>
                            每页显示{pageSize}行 <Icon type="down" />
                        </Button>
                    </Dropdown>
                    {exportButton}
                    <Pagination style={{ margin: '5px 5px' }}
                        className="ant-table-pagination"
                        total={total}
                        current={currentPage}
                        pageSize={pageSize}
                        onChange={this.pageChangeHandler.bind(this)}
                    />
                    <Button style={{ margin: 5 }} key="b_clearFilter" onClick={this.clearFilter.bind(this)}>清除过滤条件</Button>
                </div>

                {window}
            </div>
        );
    }
}
ListReportTable.propTypes = {
    reportName: PropTypes.string,
    width: PropTypes.number,
    height: PropTypes.number,
    bordered: PropTypes.bool,
    size: PropTypes.string,
    canExport: PropTypes.bool,
    canACBL: PropTypes.bool,
    canINRT: PropTypes.bool,
    canDIVI: PropTypes.bool,
    titleColNames: PropTypes.array,
};
ListReportTable.defaultProps = {
    reportName: "",
    width: 0,
    height: 0,
    bordered: true,
    size: "middle",
    canExport: true,
    canACBL: false,
    canINRT: false,
    canDIVI: false,
    titleColNames: ["账号", "子账号"]
};

export default function reportTableCreate(reportName) {
    function mapStateToProps(state) {
        const model = "ListReport_" + reportName
        const { columns, datas, total, page, pageSize, sorter, filters, visibleFilterName, controls, record, keyColumn, userIDColumn, selectedRowKeys, divi, acbl, inrt, currRowIndex } = state[model];
        const { offsetHeight, offsetWidth, collapsedLeftMenu, odsDate, cmDate, FTPDate, menus } = state.menus
        return {
            reportName: reportName,
            loading: state.loading.models[model],
            columns: columns,
            dataSource: datas,
            total,
            currentPage: page,
            sorter: sorter,
            filters: filters,
            pageSize,
            controls,
            record,
            offsetHeight,
            offsetWidth,
            collapsedLeftMenu,
            visibleFilterName,
            keyColumn,
            userIDColumn,
            selectedRowKeys,
            divi, acbl, inrt, currRowIndex, odsDate, cmDate, FTPDate, menus
        }
    }
    return connect(mapStateToProps)(ListReportTable);
}
